package httpserver
{
	import ctimer.CTimer;
	import ctimer.Task;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	
	import flashx.textLayout.factory.TruncationOptions;
	
	import mx.effects.Fade;
	
	import spark.components.mediaClasses.VolumeBar;

	/**
	*完成对web server的http请求，具有对web server的心跳功能
	* */
	public class WebServerConnection extends EventDispatcher
	{
		
		public static const HEARTBEAT_INTERVAL_TIME:int = 15;   //心跳时间间隔
		
		private var _timer:CTimer = null;
		
		private var _heartbeatTask:Task = null;
		private var _heartbeatUrl:String = null;
		
		private var _httpRequest:HttpRequest = null;
		private var _httpConnectState:Boolean = true;
		
		public function WebServerConnection()
		{
			_timer = new CTimer();
			_timer.Run();
			
		}
		
		public var _reqFinished = true;

		public function sendRequest(url:String, requestJsonData:String, responsFunction:Function):void
		{
			
			_httpRequest = new HttpRequest(url,requestJsonData,responsFunction);
			_httpRequest.addEventListener(Event.COMPLETE, onHttpRequestCompleteHandler);
			_httpRequest.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHttpStatusHandler);
			_httpRequest.addEventListener(HttpRequest.HTTP_REQUEST_ERROR, onHttpRequestErrorHandler);
			
			_httpRequest.sendRequest();
			_reqFinished = false;
		}

		public function startHeartbeat(url:String):void
		{
			
			if (url == null)
			{
				return;
			}
			
			_heartbeatUrl = url + "?random=" + Math.ceil(Math.random()*100000);
			
			_heartbeatTask = new Task(heartbeat, HEARTBEAT_INTERVAL_TIME, true);
			_timer.AddTask(_heartbeatTask);	
		}
		
		public function stopHearbeat():void
		{
		
			if (_heartbeatTask != null)
			{
				_timer.DeleteTask(_heartbeatTask);
			}
		}
		
		private function heartbeat():void
		{
			if (_heartbeatUrl == null)
			{
				return;
			}
			
			sendRequest(_heartbeatUrl, null, onHeartbeat);

		}
		
		private function onHeartbeat(jsonData:String):void
		{
			//do nothing
		}
		
		private function onHttpRequestCompleteHandler(event:Event):void
		{
			_reqFinished  = true;
			if (!_httpConnectState)
			{
				stopHearbeat(); //先停止掉心跳，防止心跳timer重复加入timer队列
				startHeartbeat(_heartbeatUrl);
				
				_httpConnectState = true;
			}
			
		}
		
		
		private function onHttpStatusHandler(event:HTTPStatusEvent):void
		{
			
			if (event.status != 200)
			{
				stopHearbeat(); //停止心跳
				
				_httpConnectState = false;	
			}
			_reqFinished = true;
		}
		
		private function onHttpRequestErrorHandler(event:Event):void
		{
			//分发网络发送请求失败消息
			dispatchEvent(event);
			_httpConnectState = false;	
			_reqFinished = true;
		}
		
		
	}
	
}